package top.ysh.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.ysh.mapper.UserMapper;
import top.ysh.pojo.User;
import top.ysh.service.UserService;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询所有用户信息
     * @return
     */
    @Override
    public List<User> findAll() {
        /*
            第一次数据走redis缓存，后面查询走redis查询
         */
        // 查询redis缓存数据
        List<User> users = (List<User>) redisTemplate.opsForList().range("users",0,-1);
        if (users != null && users.size() > 0) {
            // 如redis中存在
            return users;
        } else {
            // 走数据库查询，存入redis
            List<User> list = userMapper.findAll();
            redisTemplate.opsForList().rightPushAll("users",list);
            return list;
        }

    }

    /**
     * 新增用户信息
     *
     * @param user
     * @return
     */
    @Override
    public boolean save(User user) {
        boolean result = userMapper.save(user);
        if (result){
            // 删除redis中的缓存
            redisTemplate.delete("users");
        }
        return result;
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @Override
    public boolean update(User user) {
        boolean result = userMapper.update(user);
        if (result){
            // 删除redis中的缓存
            redisTemplate.delete("users");
        }
        return result;
    }

    /**
     * 删除用户
     *
     * @param uuid
     * @return
     */
    @Override
    public boolean delete(Integer uuid) {
        boolean result = userMapper.delete(uuid);
        if (result){
            // 删除redis中的缓存
            redisTemplate.delete("users");
        }
        return result;
    }
}
